'use strict';

exports.main = async (event, context) => {
  console.log('标记通知已读云函数被调用，参数:', event)
  
  const { notificationId, userId } = event
  
  if (!notificationId || !userId) {
    return {
      success: false,
      code: 400,
      msg: '缺少必要参数'
    }
  }

  const db = uniCloud.database()
  
  try {
    console.log(`标记通知 ${notificationId} 为已读，用户 ${userId}`)
    
    // 更新通知状态为已读
    const result = await db.collection('notification-messages')
      .where({
        _id: notificationId,
        user_id: userId // 确保只能标记自己的通知
      })
      .update({
        is_read: true,
        read_time: new Date()
      })
    
    console.log('更新结果:', result)
    
    if (result.updated > 0) {
      return {
        success: true,
        code: 200,
        msg: '标记已读成功',
        data: {
          notificationId: notificationId,
          updated: result.updated
        }
      }
    } else {
      return {
        success: false,
        code: 404,
        msg: '通知不存在或无权限'
      }
    }
    
  } catch (error) {
    console.error('标记通知已读失败:', error)
    return {
      success: false,
      code: 500,
      msg: '标记已读失败: ' + error.message,
      error: error.toString()
    }
  }
}
